package com.blank.shop.stream;

import lombok.Setter;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.http.ResponseEntity;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * EnableBinding 可以理解为是一个消息的发送管道的定义
 *
 * @author _blank
 */
@RestController
@EnableBinding(Source.class)
@SpringBootApplication
public class ShopStreamRabbitMqProviderApplication implements ApplicationContextAware {

    @Setter
    private ApplicationContext applicationContext;

    /**
     * 消息发送管道
     */
    @Resource
    private MessageChannel output;

    public String sendMsg() {
        final String alphanumeric = RandomStringUtils.randomAlphanumeric(13);

        final Message<String> message = MessageBuilder.withPayload(alphanumeric).build();
        this.output.send(message);

        return alphanumeric + "    " + System.currentTimeMillis();
    }

    /**
     * controller 服务调用，测试发一条消息
     *
     * @return org.springframework.http.ResponseEntity
     */
    @GetMapping
    public ResponseEntity<String> callSendMsg() {
        final ShopStreamRabbitMqProviderApplication bean = this.applicationContext.getBean(ShopStreamRabbitMqProviderApplication.class);
        final String sendMsg = bean.sendMsg();
        return ResponseEntity.ok(sendMsg);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(ShopStreamRabbitMqProviderApplication.class, args);
    }

}
